package com.smedi.ismedi.personnel.core.infrastructure.listener;

import com.smedi.ismedi.personnel.core.application.service.ProfileImageApplicationService;
import com.smedi.ismedi.personnel.core.infrastructure.constant.ConstantField;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xulinjun
 * @Date: 2021-6-9 15:39
 */
@Slf4j
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
    @Autowired
    ProfileImageApplicationService profileImageApplicationService;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    private List<String> getGroupPath(String expressKey, String tempPath) {
        String key = expressKey.replace(tempPath, "");
        String[] keys = key.split("\\" + ConstantField.split); // 分割
        log.info("expressKey: {}, imageUUID: {}, group: {}, path: {}", expressKey, keys[0], keys[1], keys[2]);

        return new ArrayList<String>() {{
            add(keys[1]);
            add(keys[2]);
        }};
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 捕捉符合的过期key，并调用业务逻辑
        String expressKey = new String(message.getBody(), StandardCharsets.UTF_8);
        if (expressKey.contains(ConstantField.profileImageTempPath)) {
            List<String> params = getGroupPath(expressKey, ConstantField.profileImageTempPath);
            profileImageApplicationService.dropTempProfileImage(params.get(0), params.get(1)); // 删除临时文件
        } else if (expressKey.contains(ConstantField.profileImageTempPath)) {
            List<String> params = getGroupPath(expressKey, ConstantField.signatureTempPath);
            profileImageApplicationService.dropTempProfileImage(params.get(0), params.get(1)); // 删除临时文件
        }
    }
}
